package com.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.item.mapper.RechargeRecordMapper;
import com.item.mapper.usermapper;
import com.item.pojo.*;
import com.item.service.PointsEventService;
import com.item.mapper.PointsEventMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author XXDLD
 * @description 针对表【points_event】的数据库操作Service实现
 * @createDate 2024-06-04 10:26:18
 */
@Service
public class PointsEventServiceImpl extends ServiceImpl<PointsEventMapper, PointsEvent>
        implements PointsEventService {

    @Autowired
    private RechargeRecordMapper rechargeRecordMapper;

    private final com.item.mapper.usermapper usermapper;

    public PointsEventServiceImpl(@Qualifier("usermapper") usermapper usermapper) {
        this.usermapper = usermapper;
    }

    @Override
    public void insertPointsEvent(String username) {

        if (!username.isEmpty()) {
            String event = "每日签到";
            String eventPoints = "+50";
            String eventTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            baseMapper.insertPointsEvent(username, event, eventTime, eventPoints);
        } else {
            System.out.println("用户名为空");
        }
    }

    @Override
    public List<PointsEvent> getPointsEvent(String username) {
        return baseMapper.getPointsEvent(username);
    }

    @Override
    public String pointsToBalance(String username, Integer pointsNumber, BigDecimal balance) {
        BigDecimal points = BigDecimal.valueOf(pointsNumber);
        BigDecimal balance1 = points.divide(BigDecimal.valueOf(1000));

        List<User> pointsByUsername = usermapper.getPointsByUsername(username);

        Integer allPoints;

        if (!pointsByUsername.isEmpty()) {
            allPoints = pointsByUsername.get(0).getPoints();
        } else {
            System.out.println("用户不存在或未找到积分信息");
            return "false1";
        }

        if (balance1.equals(balance)) {
            //减去积分
            if (allPoints>=pointsNumber){
                usermapper.takeOutPoints(username, pointsNumber);

                //插入积分变化事件
                String event = "积分兑换余额";
                String eventPoints = "-" + pointsNumber;
                String eventTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                baseMapper.insertPointsEvent(username, event, eventTime, eventPoints);

                //通过用户名获取用户id
                int idByUsername = Math.toIntExact(usermapper.findIdByUsername(username));
                Double balance2 = balance1.doubleValue();
                //修改余额
                usermapper.updateBalanceById(idByUsername, balance2);

                //获取总余额
                BigDecimal balanceByUsername = usermapper.getBalanceByUsername(username);
                String status = "成功";

                Random random = new Random();
                // 定义范围
                long lowerBound = 10000L;
                long upperBound = 99999L;
                // 生成在指定范围内的随机long数值
                long tradeId = lowerBound + (long) (random.nextDouble() * (upperBound - lowerBound + 1));
                // 插入余额变化记录
                rechargeRecordMapper.insertRechargeRecord(tradeId, idByUsername, balance2, balanceByUsername, status);
            }
            else {
                System.out.println("积分不足");
                return "false";
            }
        }
        return "true";
    }

    @Override
    public List<ExchangeItems> getExchangeItems() {
        return baseMapper.getExchangeItems();
    }

    @Override
    public List<Coupons> getCoupons() {
        return baseMapper.getCoupons();
    }

    @Override
    public List<LotteryItems> getLotteryItems() {
        return baseMapper.getLotteryItems();
    }

    @Override
    public String lotteryDraw(String username, Integer pointsValue) {
        //根据用户名获取用户id
        int idByUsername = Math.toIntExact(usermapper.findIdByUsername(username));

        // 获取当前日期
        LocalDate today = LocalDate.now();

        //获取用户抽奖次数
        int userDrawTimes = baseMapper.getUserDrawTimes(idByUsername,today);

        if (userDrawTimes>=5){
            return "抽奖次数已用完";
        }

        //获取用户总积分
        List<User> pointsByUsername = usermapper.getPointsByUsername(username);

        if (pointsByUsername.isEmpty()||pointsByUsername.get(0).getPoints()<pointsValue){
            return "积分不足";
        }

        // 获取抽奖项列表
        List<LotteryItems> lotteryItemsList = baseMapper.getLotteryItems();
        // 创建迭代器
        Iterator<LotteryItems> iterator = lotteryItemsList.iterator();

        // 利用迭代器遍历抽奖项列表，将数量为0的奖项移除
        while (iterator.hasNext()) {
            LotteryItems item = iterator.next();
            if (item.getNumber() <= 0) {
                iterator.remove();
                //更新抽奖状态
                baseMapper.updateStatusById(item.getLotteryItemsId());
            }
        }

        // 计算总概率
        double totalProbability = lotteryItemsList.stream().mapToDouble(LotteryItems::getProbability).sum();

        // 构建累计概率区间列表
        List<Double> probabilityList = new ArrayList<>();
        double cumulativeProbability = 0;
        for (LotteryItems item : lotteryItemsList) {
            cumulativeProbability += item.getProbability() / totalProbability;
            probabilityList.add(cumulativeProbability);
        }

        // 生成一个随机数
        Random random = new Random();
        double randomNumber = random.nextDouble();

        // 找到随机数在哪个区间
        int selectedIndex = 0;
        for (int i = 0; i < probabilityList.size(); i++) {
            if (randomNumber <= probabilityList.get(i)) {
                selectedIndex = i;
                break;
            }
        }

        // 获取被选中的奖品
        LotteryItems selectedItem = lotteryItemsList.get(selectedIndex);

        //获取抽中商品的id
        int lotteryItemsId = selectedItem.getLotteryItemsId();
        //获取抽中商品的标题
        String title = selectedItem.getTitle();

        //扣除相应的积分
        usermapper.takeOutPoints(username, pointsValue);

        //插入积分变化事件
        String event = "抽奖";
        String eventPoints = "-" + pointsValue;
        String eventTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        baseMapper.insertPointsEvent(username, event, eventTime, eventPoints);

        //被抽中奖品数量减一
        baseMapper.updateNumberById(lotteryItemsId);


        //插入用户中奖记录
        baseMapper.insertUserLotteryRecord(idByUsername,lotteryItemsId,title,today);

        int type = selectedItem.getType();

        if (type == 1){
            int value = Integer.parseInt(selectedItem.getValue());
            //抽中积分类型奖品，根据用户id更新积分
            baseMapper.updatePoints(idByUsername,value);
        }

        return String.valueOf(lotteryItemsId);
    }

    @Override
    public List<LotteryRecords> getLotteryRecords() {
        return baseMapper.getLotteryRecords();
    }

    @Override
    public String exchangeItemsType0(String username, Integer couponsId, Integer pointsNumber) {
        //根据用户名获取用户id
        int idByUsername = Math.toIntExact(usermapper.findIdByUsername(username));

        //获取已有的0类型的商品id
        List<Integer> exchangeItemIdByUsersId = baseMapper.getExchangeItemIdByUsersId(idByUsername);

        for (Integer itemId : exchangeItemIdByUsersId) {
            if (itemId.equals(couponsId)) {
                return "false1";
            }
        }

        //获取用户总积分
        List<User> pointsByUsername = usermapper.getPointsByUsername(username);

        Integer allPoints;

        if (!pointsByUsername.isEmpty()) {
            allPoints = pointsByUsername.get(0).getPoints();
        } else {
            System.out.println("用户不存在或未找到积分信息");
            return "false2";
        }

        if (allPoints>=pointsNumber){
            //扣除相应的积分
            usermapper.takeOutPoints(username, pointsNumber);

            //插入积分变化事件
            String event = "积分兑换0类型商品";
            String eventPoints = "-" + pointsNumber;
            String eventTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            baseMapper.insertPointsEvent(username, event, eventTime, eventPoints);

            //将用户id和0类型商品id插入到用户可交换商品表
            baseMapper.insertExchangeIdToUsers(idByUsername, couponsId);
        }else {
            System.out.println("积分不足");
            return "false";
        }
        return "true";
    }

    @Override
    public String exchangeItemsType1(String username,Integer pointsNumber) {
        //根据用户名获取用户当前积分
        List<User> pointsByUsername = usermapper.getPointsByUsername(username);

        Integer allPoints;

        if (!pointsByUsername.isEmpty()) {
            allPoints = pointsByUsername.get(0).getPoints();
        } else {
            System.out.println("用户不存在或未找到积分信息");
            return "false1";
        }

        if (allPoints>=pointsNumber){
            //扣除相应的积分
            usermapper.takeOutPoints(username, pointsNumber);

            //插入积分变化事件
            String event = "积分兑换1类型商品";
            String eventPoints = "-" + pointsNumber;
            String eventTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            baseMapper.insertPointsEvent(username, event, eventTime, eventPoints);

        }else {
            return "false";
        }
        return "true";
    }


    @Override
    public String exchangeItemsCoupons(String username, Integer couponsId, Integer pointsNumber) {
        //根据用户名获取用户id
        int idByUsername = Math.toIntExact(usermapper.findIdByUsername(username));

        //获取已有的用户优惠券id
        List<Integer> couponsIdByUsersId = baseMapper.getCouponsIdByUsersId(idByUsername);

        for (Integer integer : couponsIdByUsersId) {
            if (integer.equals(couponsId)) {
                return "false1";
            }
        }

        List<User> pointsByUsername = usermapper.getPointsByUsername(username);

        Integer allPoints;

        if (!pointsByUsername.isEmpty()) {
            allPoints = pointsByUsername.get(0).getPoints();
        } else {
            System.out.println("用户不存在或未找到积分信息");
            return "false2";
        }

        if (allPoints>=pointsNumber){
            //扣除相应的积分
            usermapper.takeOutPoints(username, pointsNumber);

            //插入积分变化事件
            String event = "积分兑换优惠券";
            String eventPoints = "-" + pointsNumber;
            String eventTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            baseMapper.insertPointsEvent(username, event, eventTime, eventPoints);

            //将用户id和优惠券id插入到用户优惠券表
            baseMapper.insertCouponsToUsers(idByUsername, couponsId);
        }else {
            return "false3";
        }

        return "true";
    }


    //管理部分
    @Override
    public Boolean changeLotteryItem(LotteryItems lotteryItems) {
        return baseMapper.changeLotteryItem(lotteryItems);
    }

    @Override
    public boolean addLotteryItem(LotteryItems lotteryItems) {
        return baseMapper.addLotteryItem(lotteryItems);
    }

    @Override
    public boolean deleteLotteryItem(Integer lottertyItemId) {
        return baseMapper.deleteLotteryItem(lottertyItemId);
    }

    @Override
    public boolean changeExchangeItems(ExchangeItems exchangeItems) {
        return baseMapper.changeExchangeItems(exchangeItems);
    }

    @Override
    public boolean changeCoupons(Integer id, Integer price) {
        return baseMapper.changeCoupons(id,price);
    }

    @Override
    public boolean addExchangeItems(ExchangeItems exchangeItems) {
        return baseMapper.addExchangeItems(exchangeItems);
    }

    @Override
    public boolean deleteExchangeItems(Integer exchangeItemsId) {
        return baseMapper.deleteExchangeItems(exchangeItemsId);
    }

    @Override
    public boolean deleteCoupons(Integer id) {
        return baseMapper.deleteCoupons(id);
    }

    @Override
    public List<Map<String,String>> getExchangeItemsRecords() {
        return baseMapper.getExchangeItemsRecords();
    }

    @Override
    public List<Map<String,String>> getCouponsRecords() {
        return baseMapper.getCouponsRecords();
    }

    @Override
    public List<PointsEvent> getAllPointsEvent() {
        return baseMapper.getAllPointsEvent();
    }


}




